/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.order.poa.controller;

import com.activiti.dao.model.Activiti_SubTaskInfoRO;
import com.activiti.dao.model.TaskVo;
import com.activiti.dao.service.ActivitiService;
import com.activiti.dao.service.TaskSubService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.dao.model.HrDepartment;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.vendor.dao.model.MdVendor;
import com.erp.masterdata.vendor.service.MdVendorService;
import com.erp.order.poa.dao.model.PoAgreementHead;
import com.erp.order.poa.dao.model.PoAgreementHeadBase;
import com.erp.order.poa.dao.model.PoAgreementHeadCO;
import com.erp.order.poa.service.PoAgreementHeadService;
import com.erp.order.poaeco.dao.model.PoAgreementHeadM;
import com.erp.order.poaeco.service.PoAgreementHeadMService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/web/poAgreementHeadPay")
public class PoAgreementHeadPayController extends CuxControllerSupport {

    //日志处理
    private Logger logger = LoggerFactory.getLogger(PoAgreementHeadPayController.class);

    //服务层注入
    @Autowired
    private PoAgreementHeadService poAgreementHeadService;
    @Autowired
    private PoAgreementHeadMService poAgreementHeadMService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private MdVendorService mdVendorService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private ActivitiService activitiService;
    @Autowired
    private TaskSubService taskSubService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;

    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getPoHeadList");
    }
    /**
     * 跳转到合同列表
     */
    @RequestMapping("getPoHeadList")
    public String getPoAgreementHeadList(Pages pages, PoAgreementHeadCO poAgreementHeadCO, Model model) {
        //分页查询数据
        if (pages.getPage() == 0) {
            pages.setPage(1);
        }
        //分页查询数据
        List<PoAgreementHead> poAgreementHeadList = this.poAgreementHeadService.getDataObjectsForDataAuth("", pages, poAgreementHeadCO);
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();
        //审批状态
        Map approveStatusMap = this.datasetCommonService.getApproveStatus();
        //页面属性设置
        model.addAttribute("poHeadList", poAgreementHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        return "basic.jsp?content=poa/poaList";
    }
    /**
     * 跳转合同起草页面
     */
    @RequestMapping("goToPoHeadAdd")
    public String goToPoHeadAdd(PoAgreementHeadBase poAgreementHead, Model model) {
        //初始化默认字段
        poAgreementHead.setAmount(BigDecimal.ZERO);
        poAgreementHead.setPrepayAmount(BigDecimal.ZERO);
        poAgreementHead.setReceiveStatus("N");
        poAgreementHead.setPaymentStatus("N");
        poAgreementHead.setStatus("NEW");
        //自动生成合同编码和合同单号
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        HrDepartment hrDepartmentget = this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
        String code = this.poAgreementHeadService.getCodeAutomatic(hrDepartmentget.getShortName());
        poAgreementHead.setProjectCode(code.substring(code.length()-5));//合同编码
        poAgreementHead.setPoHeadCode(code);//合同编码
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();

        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        return "basic.jsp?content=poa/poaAdd";
    }

    /**
     * 跳转合同编辑表单页面
     */
    @RequestMapping("getPoHead")
    public String getPoAgreementHead(PoAgreementHeadBase poAgreementHead, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
        }
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();

        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        return "basic.jsp?content=poa/poaEdit";
    }

    /**
     * 跳转合同查看页面
     */
    @RequestMapping("getPoHeadView")
    public String getPoAgreementHeadView(PoAgreementHeadBase poAgreementHead, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
            if(poAgreementHead.getProcessInstanceId()!=null){
                //根据流程id获取流程审批信息
                List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementHead.getProcessInstanceId());
                model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
            }
        }
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();

        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        return "basic.jsp?content=poa/poaView";
    }


    /**
     * 跳转合同会签单页面
     */
    @RequestMapping("getPoHeadTable")
    public String getPoAgreementHeadTable(PoAgreementHeadBase poAgreementHead, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
            if(poAgreementHead.getProcessInstanceId()!=null){
                //根据流程id获取流程审批信息
                List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjectsListOnlyLastTrue(poAgreementHead.getProcessInstanceId());
                model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
            }
        }
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();

        //获取供应商信息
        MdVendor mdVendor = mdVendorService.getDataObject(Integer.parseInt(poAgreementHead.getStaffCode()));

        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("mdVendor", mdVendor);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSourceMap", poSourceMap);
        return "poa/poaTable";
    }


    /**
     * 编辑合同信息
     */
    @RequestMapping("editPoHead")
    public String editPoAgreementHead(@Valid PoAgreementHead poAgreementHead,String nextapproverid, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if (errorMap.size() > 0) {
            return "forward:getPoHead";
        }
        try {
            boolean isAdd = true;//是否是添加操作
            if(poAgreementHead.getPoHeadId()!=null && !"".equals(poAgreementHead.getPoHeadId())){ isAdd=false;}
            //保存编辑的数据
            if (isAdd) {
                poAgreementHead.setCreatedDate(new Date());
            }
            this.poAgreementHeadService.insertOrUpdateDataObject(poAgreementHead);
            if (isAdd) {
                //获取当前用户职员信息
                HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
                HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
                staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
                staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
                Map params = new HashMap<String, Object>();
                params.put("panen", staffInfo.getStaffCode());//发起人
                params.put("flzgsp_id", this.activitiService.getStaffByPosition("SPB","298"));//法律主管审批
                if("0".equals(staffInfo.getIscompany())){
                    params.put("bmfzr_id", this.activitiService.getStaffByPosition(staffInfo.getDepartmentCode(),"290"));//单位/部门负责人审批
                }else{
                    params.put("bmfzr_id", this.activitiService.getStaffByPosition(staffInfo.getDepartmentCode(),"291"));//单位/部门负责人审批
                }
                params.put("fgkjsp_id", nextapproverid);//分管会计审批
                params.put("htzgsp_id", this.activitiService.getStaffByPosition("SPB","289"));//合同主管审批
                params.put("htglbmfzr_id", this.activitiService.getStaffByPosition("SPB","300"));//合同主管审批
                params.put("gszyldsp_id", this.activitiService.getStaffByPosition("SPB","302"));//公司主要领导审批
                params.put("gsdwsjsp_id", this.activitiService.getStaffByPosition("SPB","303"));//公司党委书记审批

                //启动流程
                ProcessInstance processInstance = activitiService.erpStartProcessInstance(CommonUtils.PROCESS_DEGINITION_KEY,"web/poAgreementHead/getPoHeadApproval?poHeadCode="+poAgreementHead.getPoHeadCode(),params,CommonUtils.ACTIVITI_AGREEMENT_BUS_ID);
                //更新流程实例id
                poAgreementHead.setProcessInstanceId(processInstance.getProcessInstanceId());
                this.poAgreementHeadService.updateDataObject(poAgreementHead);
                //更新审核状态
                this.poAgreementHeadService.updateApproveStatus(poAgreementHead.getPoHeadCode(), "SUBMIT");
                //流程发起者完成当前任务节点
                Task task = activitiService.erpFindPersonalTaskByPid(processInstance.getProcessInstanceId());
                activitiService.erpCompletTask(task.getId(),null,null);
                //保存审批结果和意见
                this.poAgreementHeadService.saveActivitiTaskInfo(poAgreementHead.getPoName()+"(合同签批)",staffInfo,task,processInstance,"1");
                this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"1","1",staffInfo.getStaffName()+"发起合同签批");
            }
            attr.addFlashAttribute("hint", "success");
            /*attr.addAttribute("poHeadCode", poAgreementHead.getPoHeadCode());*/
        } catch (Exception e) {
            if (e.getCause().getClass() == ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "合同编码已存在，请重新输入");
                return "redirect:getPoHeadList";
            } else {
                throw e;
            }
        }
        return "redirect:getPoHeadList";
    }

    /**
     * 保存/编辑支付情况信息
     */
    @ResponseBody
    @RequestMapping("savePoAgreementHeadM")
    public String savePoAgreementHeadM(@RequestBody PoAgreementHeadM poAgreementHeadM) {
        this.poAgreementHeadMService.insertOrUpdateDataObject(poAgreementHeadM);
        return JsonDataUtil.getExecuteJson(0);
    }
    /**
     * 删除支付情况信息
     */
    @ResponseBody
    @RequestMapping("deletePoAgreementHeadM")
    public String deletePoAgreementHeadM(@RequestBody PoAgreementHeadM poAgreementHeadM) {
        this.poAgreementHeadMService.deleteDataObject(poAgreementHeadM);
        return JsonDataUtil.getExecuteJson(0);
    }
    /**
     * 查询支付情况信息
     */
    @ResponseBody
    @RequestMapping("getPoAgreementHeadMList")
    public List<PoAgreementHeadM> getPoAgreementHeadMList(String poHeadCode) {
        List<PoAgreementHeadM> poAgreementHeadMList = this.poAgreementHeadMService.getDataObjects(poHeadCode);
        return poAgreementHeadMList;
    }

    //文件上传保存到服务器
    @ResponseBody
    @RequestMapping("file")
    public List fileUpload(@RequestParam("imgs") List<MultipartFile> files, HttpServletRequest req) throws IOException {
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd");
        String format=sdf.format(new Date());
        String imagePathRoot = req.getServletContext().getRealPath("/")+format;
        File file = new File(imagePathRoot);

        if (!file.exists()) {
            file.mkdirs();
        }
        List list=new ArrayList();
        int i=0;
        for (MultipartFile f : files) {
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
            String dateString = formatter.format(currentTime);
            String fileName = f.getOriginalFilename();
            String imageFilePath = imagePathRoot + dateString + fileName;
            f.transferTo(new File(imageFilePath));
            String url=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+format+dateString+fileName;
            list.add(url);
        }
        System.out.println(list.toString());

        Map map=new HashMap();
        map.put("msg","succ");
        return list;
    }

    /**
     * 删除合同数据
     */
    @RequestMapping("deletePoHead")
    public String deletePoAgreementHead(PoAgreementHead poAgreementHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if (poAgreementHead != null && poAgreementHead.getPoHeadId() != null && StringUtils.isNotBlank(poAgreementHead.getPoHeadCode())) {
            if (poAgreementHead.getStatus().equals("NEW")) {
                PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
                //删除数据
                this.poAgreementHeadService.deleteDataObject(poAgreementHead);
                if(poAgreementHeadTemp.getProcessInstanceId() != null && !"".equals(poAgreementHeadTemp.getProcessInstanceId())){
                    this.activitiService.deleteProcessInstance(poAgreementHeadTemp.getProcessInstanceId());
                }
                if(poAgreementHeadTemp.getStopProcessInstanceId() != null && !"".equals(poAgreementHeadTemp.getStopProcessInstanceId())){
                    this.activitiService.deleteProcessInstance(poAgreementHeadTemp.getStopProcessInstanceId());
                }
                //提示信息
                attr.addFlashAttribute("hint", "success");
            } else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态不能删除");
            }
        }
        return "redirect:getPoHeadList";
    }

    /**
     * 根据编码查询供应商信息
     */
    @ResponseBody
    @RequestMapping("getMdVendor")
    public MdVendor getMdVendor(MdVendor mdVendor) {
        return mdVendorService.getDataObject(mdVendor.getVendorId());
    }


    /**
     * 跳转流程任务列表界面
     */
    @RequestMapping("todoPage")
    public String todoPage(Model model) {
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        //List<TaskVo> tasklist  = activitiService.erpFindPersonalTaskList(staffInfo);
        List<TaskVo> tasklist =this.activitiService.queryTaskInfo(this.activitiService.erpFindPersonalTaskList(staffInfo));

        //页面属性设置
        model.addAttribute("tasklist", tasklist);
        return "basic.jsp?content=activitiPage/todoPage";
    }

    /**
     * 跳转合同签批流程审批界面
     * id 是任务id（taskid）
     */
    @RequestMapping("getPoHeadApproval")
    public String getPoHeadApproval(PoAgreementHeadBase poAgreementHead,String id, Model model) {
        //查询要编辑的数据
        PoAgreementHeadBase poAgreementHeadTemp = this.poAgreementHeadService.getDataObject(poAgreementHead.getPoHeadCode());
        if (poAgreementHeadTemp != null) {
            poAgreementHead = poAgreementHeadTemp;
        }
        if(poAgreementHead.getProcessInstanceId()!=null){
            //根据流程id获取流程审批信息
            List<Activiti_SubTaskInfoRO> activiti_subTaskInfoList = taskSubService.getDataObjects(poAgreementHead.getProcessInstanceId());
            model.addAttribute("subTaskInfoList", activiti_subTaskInfoList);
        }
        //合同性质
        Map poQualeMap = this.datasetCommonService.getPOType();
        //合同类型
        Map poTypeMap = this.datasetCommonService.getPOAType();
        //合同类别
        Map poCateMap = this.datasetCommonService.getPOACategory();
        //合同结算方式
        Map poSettleMap = this.datasetCommonService.getPOASettleStyle();
        //合同来源方式
        Map poSourceMap = this.datasetCommonService.getPOASourceMode();
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //状态
        Map poStatusMap = this.datasetCommonService.getPOAStatus();

        Task task = taskService.createTaskQuery().taskId(id).singleResult();//获取流程代办任务
        if("合同主管审批".equals(task.getName())){
            model.addAttribute("selectShow", 1);
        }
        //页面属性设置
        model.addAttribute("poHead", poAgreementHead);
        model.addAttribute("poQualeMap", poQualeMap);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poCateMap", poCateMap);
        model.addAttribute("poSettleMap", poSettleMap);
        model.addAttribute("poSourceMap", poSourceMap);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("taskId", id);
        return "basic.jsp?content=poa/approval";
    }

    /**
     * 完成流程代办任务
     */
    @RequestMapping("doCompletTask")
    public String doCompletTask(String tab,String taskId,String processInstanceId,String nextapproverid,String nextapproverid1,String poHeadCode,String result, String content, Model model) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        Map<String,String> nextapproverids = new HashMap<>();
        if(nextapproverid !=null && nextapproverid1 != null){
            nextapproverids.put("znbmfzr_id",nextapproverid);
            nextapproverids.put("fgldsp_id",nextapproverid1);
        }
        activitiService.erpCompletTask(taskId,result,nextapproverids);
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        HrDepartment hrDepartmentget=this.hrCommonService.getHrDepartmentParentCompany(staffInfo.getDepartmentCode());
        staffInfo.setCompanyName(hrDepartmentget.getDepartmentName());
        staffInfo.setCompanyCode(hrDepartmentget.getDepartmentCode());
        //判断流程是否结束
        ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if(processInstance1==null){
            //更新表单的状态（审核中-->审核完成）
            this.poAgreementHeadService.updateStatus(poHeadCode,"0".equals(tab)?"CONFIRM":"CANCEL");
            this.poAgreementHeadService.updateApproveStatus(poHeadCode, "COMPLETE");
            this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"4",result,content);//状态  1-待审批 2-审批中 3-驳回 4-完成
        }else{
            //判断流程审批是否驳回
            if("0".equals(result)){
                this.poAgreementHeadService.updateApproveStatus(poHeadCode, "REJECT");
                this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"3",result,content);
            }else{
                this.poAgreementHeadService.updateApproveStatus(poHeadCode, "APPROVE");
                this.poAgreementHeadService.saveSubActivitiTaskInfo(staffInfo,task,processInstance,"2",result,content);
            }
        }
        return "redirect:todoPage";
    }

    @RequestMapping("graphHistoryProcessInstance")
    public void processTracking(String processInstanceId, HttpServletResponse response) throws Exception {
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String procDefId = processInstance.getProcessDefinitionId();

        // 当前活动节点、活动线
        List<String> activeActivityIds = new ArrayList<>(), highLightedFlows;
        //所有的历史活动节点
        List<String> highLightedFinishes = new ArrayList<>();

        // 如果流程已经结束，则得到结束节点
        if (!isFinished(processInstanceId)) {
            // 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
        }

        // 获得历史活动记录实体（通过启动时间正序排序，不然有的线可以绘制不出来）
        List<HistoricActivityInstance> historicActivityInstances = historyService
                .createHistoricActivityInstanceQuery().processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime().asc().list();

        for(HistoricActivityInstance historicActivityInstance : historicActivityInstances){
            highLightedFinishes.add(historicActivityInstance.getActivityId());
        }
        // 计算活动线
        highLightedFlows = getHighLightedFlows(
                (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                        .getDeployedProcessDefinition(procDefId),
                historicActivityInstances);

        if (null != activeActivityIds) {
            InputStream imageStream = null;
            try {
                response.setContentType("image/png");
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                // 获得流程引擎配置
                ProcessEngineConfiguration processEngineConfiguration = processEngine.getProcessEngineConfiguration();
                // 根据流程定义ID获得BpmnModel
                BpmnModel bpmnModel = repositoryService.getBpmnModel(procDefId);
                // 输出资源内容到相应对象
                imageStream = new DefaultProcessDiagramGenerator().generateDiagram(
                        bpmnModel, "png", activeActivityIds, highLightedFlows, "宋体", "宋体",
                        "宋体", processEngineConfiguration.getClassLoader(), 1.0);
                int len;
                byte[] b = new byte[1024];

                while ((len = imageStream.read(b, 0, 1024)) != -1) {
                    response.getOutputStream().write(b, 0, len);
                }
            } finally {
                if(imageStream != null){
                    imageStream.close();
                }
            }
        }
    }

    public boolean isFinished(String processInstanceId) {
        return historyService.createHistoricProcessInstanceQuery().finished().processInstanceId(processInstanceId).count() > 0;
    }

    /**
     * @title getHighLightedFlows
     * @description: 获取流程应该高亮的线
     * @param processDefinitionEntity 流程定义实例
     * @param historicActivityInstances 流程活动节点实例
     * @return: java.util.List<java.lang.String>
     */
    public List<String> getHighLightedFlows(ProcessDefinitionEntity processDefinitionEntity, List<HistoricActivityInstance> historicActivityInstances) {

        List<String> highFlows = new ArrayList<>();// 用以保存高亮的线flowId
        List<String> highActivitiImpl = new ArrayList<>();

        for(HistoricActivityInstance historicActivityInstance : historicActivityInstances){
            highActivitiImpl.add(historicActivityInstance.getActivityId());
        }
        for(HistoricActivityInstance historicActivityInstance : historicActivityInstances){
            ActivityImpl activityImpl = processDefinitionEntity.findActivity(historicActivityInstance.getActivityId());
            List<PvmTransition> pvmTransitions = activityImpl.getOutgoingTransitions();
            // 对所有的线进行遍历
            for (PvmTransition pvmTransition : pvmTransitions) {
                // 如果取出的线的目标节点存在时间相同的节点里，保存该线的id，进行高亮显示
                ActivityImpl pvmActivityImpl = (ActivityImpl) pvmTransition.getDestination();
                if (highActivitiImpl.contains(pvmActivityImpl.getId())) {
                    highFlows.add(pvmTransition.getId());
                }
            }
        }

        return highFlows;
    }
}
